/**
 * @classDescription Ajax封装类
 * @author Tousin
 */
/**
 * @constructor
 */
Ajax.Connection = function(){
	if(Ajax.Connection.inactive){
		throw new Error("Internet Connection is inactive!");
	}
	this.link = new Ajax.HttpRequest();
//	this.buffer = new Util.Map();
	this.currentID = 0;
}
/**
 * @property　标定当前seesion是否丢失
 * @type {Boolean}
 */
Ajax.Connection.sessionLost = false;
/**
 * @property 当前网络连接是否可用
 * @type {Boolean}
 */
Ajax.Connection.inactive = false;
/**
 * 发送一个异步请求.
 * 
 * @param {Object} url
 * @param {Object} param
 * @param {Object} callbackFunc
 * @param {Object} waitFunc
 */

Ajax.Connection.prototype.getString = function(url, param,callbackFunc,waitFunc){
	var link = this.link;
	var _this = this;
	
	link.onreadystatechange = function(){
		
		if (link.readyState == 4) {
			if (link.status == 200) {
				if(callbackFunc){
					callbackFunc(link.responseText);
				}
			}
			else {
				_this.exceptionHandler(link);
			}
		}
		else {
			if(waitFunc){
				waitFunc();
			}
		}	
	}
	
	link.open("POST", encodeURI(url), true);
	link.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	link.send(encodeURI(param + "&ran=" + Math.random()));
}
/**
 * 发送一个同步请求
 * @param {Object} url
 * @param {Object} param
 * @param {Object} callbackFunc
 */
Ajax.Connection.prototype.synGetString = function(url, param){
	var link = this.link;	
//	alert(param.substr(0,100));
	link.open("POST", encodeURI(url), false);
	link.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	
/*	if(param){
		link.setRequestHeader("Content-length",param.length);
	}
*/	
	link.send(encodeURI(param+"&ran="+Math.random()));
	
	return link.responseText;
}

/**
 * 发送一个异步请求返回一个XML格式的文档树
 * @param {Object} url
 * @param {Object} param
 * @param {Object} callbackFunc
 * @param {Object} waitFunc
 */

Ajax.Connection.prototype.getXML = function(url, param,callbackFunc,waitFunc){
	var link = this.link;
	var _this = this;
	
	link.onreadystatechange = function(){
		
		if (link.readyState == 4) {
			if (link.status == 200) {
				if(callbackFunc){
					callbackFunc(link.responseXML);
				}
			}
			else {
			//	alert("error : " + link.status+"\n"+link.responseText);
			}
		}
		else {
			if(waitFunc){
				waitFunc();
			}
		}	
	}
	
	link.open("POST", encodeURI(url), true);
	link.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	link.send(encodeURI(param+"&ran="+Math.random()));
}
/**
 * 发送一个同步请求，返回一个XML文档树
 * @param {Object} url
 * @param {Object} param
 * @param {Object} callbackFunc
 */
Ajax.Connection.prototype.synGetXML = function(url, param){
	var xmlDoc;
	var _this = this;
	var link = this.link;

//	link.overrideMimeType('text/xml');
	
	try {
		link.open("POST", encodeURI(url), false);
		link.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		link.send(param+"&ran="+Math.random());	
		
		//如果不加这一句判断，在Firefox下当服务器返回NULL时，Firefox检测不到异常。
		if(link.responseText === "null"){
			throw new Error("request url reply null ! ");
		}
		xmlDoc = link.responseXML;
		
	}
	catch(e){
		alert(e);
	//	new UI.OptionFrame.showErrorMessage("网络连接已经断开！");
	}
	return xmlDoc;
}


Ajax.Connection.prototype.get = function(beanFunc,url,successFunc,waitFunc,failFunc){
	var xmlDoc;
	var _this = this;
	var link = this.link;
	var b ;
//	link.overrideMimeType('text/xml');
	link.onreadystatechange = function() {
		if (link.readyState == 4) {
			if (link.status == 200) {
				//如果不加这一句判断，在Firefox下当服务器返回NULL时，Firefox检测不到异常。
				if(link.responseText === "null"){
					throw new Error("request url reply null ! ");
				}
				xmlDoc = link.responseXML;
				//	alert(xmlDoc.toString());
				//  alert(link.responseText);
				b = _this.parseBean(beanFunc, xmlDoc);
				
				successFunc(b);
			} else {
				if(failFunc){
					failFunc();
				}
				else{
				//	alert("error : " + link.status);
				}
			}
		} else {
			if(waitFunc)waitFunc();
		}
	};
	try {
		//alert(url);
	/*	link.open("GET", encodeURI(url), true);
		link.send(null);
	*/	
		link.open("POST", encodeURI(url), true);
		link.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		link.send("ran="+Math.random());			
	}
	catch(e){
//		new UI.OptionFrame.showErrorMessage("网络连接已经断开！");
//		alert("get   "+Core.netTray);
	//	Core.taskBar.iconBar.deleteIcon(Core.netTray);
	//	Core.netTray = Core.taskBar.iconBar.addIcon("网络连接已断开","image/UI/TaskIconBar/offline.gif",function(){alert("T has been clicked")});
		return this.exceptionHandler(beanFunc);
	}
}

/**
 * 基于同步获取的 get 方法
 * @param {Object} beanFunc
 * @param {Object} url
 * @param {Object} waitFunc
 */
Ajax.Connection.prototype.synGet = function(beanFunc,url,waitFunc){
	var xmlDoc;
	var _this = this;
	var link = this.link;
	var b ;
//	link.overrideMimeType('text/xml');
	link.onreadystatechange = function() {
		if (link.readyState == 4) {
			if (link.status == 200) {
				
			} else {
			//	alert("error : " + link.status);
			}
		} else {
			if(waitFunc){
				waitFunc(link.readyState);
			}
		}
	};
	try {
		//alert(url);
	/*	link.open("GET", encodeURI(url), false);
		link.send(null);	
	*/	
		link.open("POST", encodeURI(url), false);
		link.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		link.send("ran="+Math.random());
		
		//如果不加这一句判断，在Firefox下当服务器返回NULL时，Firefox检测不到异常。
		if(link.responseText === "null"){
			throw new Error("request url reply null ! ");
		}
		else if(link.responseText === "success_no_data"){
			return [];
		}
		
		xmlDoc = link.responseXML;
		//	alert(xmlDoc.toString());
		//  alert(link.responseText);
		b = _this.parseBean(beanFunc, xmlDoc);	
	}
	catch(e){
	//	new UI.OptionFrame.showErrorMessage("网络连接已经断开！");
		return this.exceptionHandler(beanFunc,link);
	}
	return b;
}

Ajax.Connection.prototype.parseBean = function(beanFunc,xmlDoc){
	if(xmlDoc == null){
		throw new Error("xmlDoc is null exception!");
	}
	
	var element;
	try {
		element = xmlDoc.firstChild.nextSibling.firstChild;
	} 
	catch (e) {
		//IE与FF在对XML的封装上的不一致，导致这里需要做这样的处理
		element = xmlDoc.firstChild.firstChild;
	}

	var beans = new Array();
//	var fields;
//	eval("fields = new Data.BeanReflect.getFields(Data.Beans."+beanName+");");
	
	while(element){
		var bean = new beanFunc();
		
		if(!bean){
			alert("beanName is not found !");
		}
		
		for(name in bean){
			try {			
				bean[name] = element.getElementsByTagName(name)[0].firstChild.nodeValue;
			}
			catch(e){
				bean[name] = bean[name]?bean[name]:"";
			}
			
		}
		
		if(beanFunc == Data.Beans.File && bean.provider == "system"){
			begin = Date.parse("2010/12/23");
			var mill = new Date().getTime()-begin;
			bean.id = parseInt(bean.id);
			bean.up = parseInt(bean.up)+Math.round(Math.log(mill)/Math.log(1.4)+Math.pow(bean.id,2)%79);
		}
	/*	
		bean.name = element.getElementsByTagName("name")[0].firstChild.nodeValue;
		bean.id = element.getElementsByTagName("id")[0].firstChild.nodeValue;
		bean.path = element.getElementsByTagName("path")[0].firstChild.nodeValue;
		bean.size = element.getElementsByTagName("length")[0].firstChild.nodeValue;
		bean.size = (bean.size/1000)+"kb";
		bean.usedCount = element.getElementsByTagName("usedCount")[0].firstChild.nodeValue;
		bean.isShared = element.getElementsByTagName("isShared")[0].firstChild.nodeValue;
		bean.type = element.getElementsByTagName("suffix")[0].firstChild.nodeValue;
		bean.lastModifyDate = element.getElementsByTagName("lastModifyDate")[0].firstChild.nodeValue;
	*/	
		beans.push(bean);
		
		element = element.nextSibling;
	}
	
	return beans;
}
/**
 * 弹出下载框下载给定路经的文件
 * @param {Object} filePath
 */
Ajax.Connection.prototype.download = function(filePath,isDirectDownload){
	window.open(encodeURI("osentry?command=os:download:" + encodeURIComponent(filePath) + (isDirectDownload === false?";false":";true")));
}

Ajax.Connection.prototype.downloadPublicFile = function(filePath,isDirectDownload){
	window.open(encodeURI("osentry?command=os:downloadPublicFile:" + encodeURIComponent(filePath) + (isDirectDownload === false?";false":";true")));
}

Ajax.Connection.prototype.downloadById = function(id,isDirectDownload){
	window.open(encodeURI("osentry?command=os:downloadById:" + id + (isDirectDownload === false?";false":";true")));
}

/**
 * 
 * @param {Object} filePath
 * @param {Object} successFunc
 * @param {Object} waitFunc
 * @param {Object} failFunc
 */
Ajax.Connection.prototype.del = function(filePath,successFunc,waitFunc,failFunc){
//	alert(filePath);
	var success = function(res){
		if(res === "success"){
			successFunc();
		}
		else{
			failFunc();
		}
	}

	//var aa = this.getString(encodeURI("IndividualFilesList"),encodeURI("command=del:"+filePath),success,waitFunc);
	//alert(filePath);
	var aa = this.getString("osentry","command=os:del:"+encodeURIComponent(filePath),success,waitFunc);

}

Ajax.Connection.prototype.exceptionHandler = function(link){
	if(link && link.readyState == 4 && (link.status == 0 || link.status == 12029)){
		var _this = this;
		//如果已经断网了，则说明下面的代码已经被执行，不重复执行
		if(Ajax.Connection.inactive){
			return;
		}
		
		Ajax.Connection.inactive = true;
		Core.appManager.setAppEnable(false);
		
		var onNetInActive = function(){
			if(Core.taskBar){	
				Core.taskBar.iconBar.deleteIcon(Core.netTray);
				Core.netTray = Core.taskBar.iconBar.addIcon("网络连接已断开","",function(){});
				
				var success = function(res){
					if(res != "ping"){
						return;
					}
					
					clearInterval(inter);
					Ajax.Connection.inactive = false;
				//	alert("会话已经过期，可能同一账号在其它地方登录所导致，您可以再次登录！");
					Core.taskBar.iconBar.deleteIcon(Core.netTray);
					Core.netTray = Core.taskBar.iconBar.addIcon("已连接Internet","image/UI/TaskIconBar/online.gif",function(){});				
					Core.appManager.setAppEnable(true);
					if(Core.connManager){
						 Core.connManager.sendCommand("pull");
					}
				}
				
				var inter = setInterval(function(){					
					var link_test = new Ajax.HttpRequest();
					var _this = this;
	
					link_test.onreadystatechange = function(){
						if (link_test.readyState == 4) {
							if (link_test.status == 200) {
								success(link_test.responseText);
							}
						}
					}
	
					link_test.open("POST", "osentry?command=os:test:ping", true);
					link_test.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					link_test.send("ran=" + Math.random());
				},1000);
			}
		}
		
		var onNetActive = function(){
			alert("与服务器通信意外中断，请重新登录");
			window.location.href = "login.html";
		}
		
		var img = document.createElement('img');
		img.onerror = onNetInActive;
		img.onload = onNetActive;
		img.src = "http://gimg.baidu.com/img/gs.gif?ran="+Math.random();
		
			
	}
	else{
	//	alert("会话已经过期，可能同一账号在其它地方登录所导致，您可以再次登录！");
	}	
}
